package ua.kiev.tosik.price.gui;

import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.conf.Language;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Tray {

	private TrayIcon trayIcon;
	private SystemTray tray;
	private Language lang;

	public Tray() {
		lang = Language.getInstance();
		if (SystemTray.isSupported()) {
			final JPopupMenu menu = new JPopupMenu(lang.get("app.title"));
			int size = MainMenu.getInstance().getfMenuList().size();
			int i = 0;
			for ( JMenuItem p: MainMenu.getInstance().getfMenuList() ) {
				i++;
				if ( i == size ) {
					menu.addSeparator();
				}
				JMenuItem n = new JMenuItem(p.getText(), p.getIcon());
				if ( p.getActionListeners().length > 0 ) {
					n.addActionListener( p.getActionListeners()[0] );
				}
				menu.add(n);
			}
			/*
			JMenuItem exit = new JMenuItem(MenuConfig.getInstance().get("Quit"), new ImageIcon("images/Cancel16.png"));
			JMenuItem reload = new JMenuItem(MenuConfig.getInstance().get("RefreshData"), new ImageIcon("images/Refresh16.png"));
			menu.add(reload);
			menu.addSeparator();
			menu.add(exit); */

			trayIcon = new TrayIcon(new ImageIcon(AppConfig.getInstance().get("app.icon")).getImage(), lang.get("app.title"), null);
			tray = SystemTray.getSystemTray();

			trayIcon.addMouseListener(new MouseAdapter() {
				public void mouseReleased(MouseEvent e) {
					if (e.isPopupTrigger()) {
						menu.setLocation(e.getX(), e.getY()-60);
						menu.setInvoker(menu);
						menu.setVisible(true);
					}
				}
			});

			try {
				tray.add(trayIcon);
			} catch (AWTException e) {
				System.err.println(e);
			}
		}
	}

	public void destroy() {
		tray.remove(trayIcon);
	}

}
